package restful.struts2.handler;

import static restful.struts2.Slurp.*;

import java.io.*;

public class JsonOrQueryStringHandler implements ContentTypeHandler {
	private JsonLibHandler jsonHandler = new JsonLibHandler();

	public String fromObject(Object obj, String resultCode, Writer toStream) {
		return jsonHandler.fromObject(obj, resultCode, toStream);
	}

	public String getContentType() {
		return "application/json";
	}

	public String getExtension() {
		return "json";
	}

	public boolean isJson(String string) {
		boolean startsWithBranch = string.startsWith("{");

		return startsWithBranch;
	}

	public boolean isQueryString(String string) {
		boolean notStartWithBranch = !string.startsWith("{");
		boolean containsEqual = string.contains("=");

		return notStartWithBranch && containsEqual;
	}

	public Object toObject(Reader in, Object target) {
		return toObject(slurp(in), target);
	}

	public Object toObject(String input, Object target) {
		if (isJson(input)) return jsonHandler.toObject(input, target);
		if (isQueryString(input)) return target;
		throw new RuntimeException("expected input in json or query string format");
	}
}